<!-- 订单签名 -->
<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "@/request";
import { Check } from "@element-plus/icons-vue";

import { getOrderDetails, getContractDetails } from "../apis/order.js";

const route = useRoute();
const router = useRouter();
const contractItems = ref();
const orderInfo = ref();
const contractInfo = ref();
const loading = ref(true);
const wechatCode = ref("");
// 获取订单信息
const getOrder = () => {
  let orderId = route.query.id;

  getOrderDetails(orderId)
    .then((res) => {
      console.log(res, "获取订单信息");
      // alert("res.data" + JSON.stringify(res.data));
      // return;
      orderInfo.value = res.data;
      getContract();
    })
    .catch((err) => {
      console.log(err, "获取订单信息");
    });
  return;
  axios
    .get(`/api/order/${orderId}`)
    .then((result) => {
      const { status, data } = result;
      if (status === 200) {
        orderInfo.value = data;
        getContract();
      }
    })
    .catch((err) => {});
};
// 获取合同信息
const getContract = () => {
  let orderId = route.query.id;
  return new Promise((resolve, reject) => {
    getContractDetails(orderId)
      .then((res) => {
        if (res.data) {
          contractInfo.value = res.data;
          contractItems.value = res.data.items;
          loading.value = false;
          resolve();
        } else {
          ElMessage({
            message: "还没有合同.",
            type: "warning",
          });
          router.push("/orderQuery");
        }
      })
      .catch((err) => {
        reject(err);
      });
    return;
    axios
      .get(`/api/contract/${orderId}`)
      .then((result) => {
        const { status, data } = result;
        if (status === 200) {
          if (data) {
            contractInfo.value = data;
            contractItems.value = data.items;
            loading.value = false;
            resolve();
          } else {
            ElMessage({
              message: "还没有合同.",
              type: "warning",
            });
            router.push("/orderQuery");
          }
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// h5授权
const wechatH5Auth = () => {
  const backUrl = location.href;
  location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx37b007893669687c&redirect_uri=${backUrl}&response_type=code&scope=snsapi_userinfo&state=sq&connect_redirect=1#wechat_redirect`;
};
getOrder();
/**
 * 去签字
 */
const goToContractInfo = () => {
  // 判断是否微信授权
  if (contractInfo.value.signature) {
    goToPay();
  } else {
    let orderId = route.query.id;
    router.push("/contractInfo?id=" + orderId);
  }
};
// 生成支付订单串
const buildPayUrl = () => {
  const body = {
    subject: orderInfo.value.name + "的订单",
    total_amount: orderInfo.value.sum,
    out_trade_no: orderInfo.value.order,
    code: wechatCode.value,
  };
  axios
    .post(`/api/wechatPay/payment`, body)
    .then((result) => {
      console.log(result, "result");
      if (result.data.success) {
        callWechatPay(result.data.paymentUrl);
      }
    })
    .catch((err) => {});
};
// 调用微信支付弹窗
const callWechatPay = (payArgs) => {
  WeixinJSBridge.invoke("getBrandWCPayRequest", payArgs, function (res) {
    if (res.err_msg == "get_brand_wcpay_request:ok") {
      ElMessage({
        message: "支付成功.",
        type: "success",
      });
      getOrder();
    } else {
      ElMessage({
        message: "支付失败.",
        type: "warning",
      });
    }
  });
};
/**
 * 去支付
 */
const goToPay = () => {
  buildPayUrl();
};
onMounted(() => {
  document.title = "支付";
  const ua = navigator.userAgent.toLowerCase();
  // alert("onMounted：" + JSON.stringify(ua));
  if (ua.indexOf("micromessenger") != -1) {
    const code = localStorage.getItem("code");
    // alert("code" + JSON.stringify(code));
    // alert("code" + code);
    // alert(
    //   'route.query.hasOwnProperty("code")' +
    //     JSON.stringify(route.query.hasOwnProperty("code"))
    // );
    if (route.query.hasOwnProperty("code") && !code) {
      wechatCode.value = route.query.code;
      localStorage.setItem("code", route.query.code);
    } else {
      // 没有微信授权登录
      localStorage.removeItem("code");
      wechatH5Auth();
    }
  } else {
    // 不在微信中
    ElMessage({
      message: "请在微信内打开该网页.",
      type: "warning",
    });
  }
});
</script>

<template>
  <div class="order_signature_view" v-loading="loading">
    <ul class="order_signature" v-if="!loading">
      <li class="order_item">
        <span>订单编号:</span>
        <span>{{ orderInfo.order }}</span>
      </li>
      <li class="order_item">
        <span>车主姓名:</span>
        <span>{{ orderInfo.name }}</span>
      </li>
      <li class="order_item">
        <span>车牌号:</span>
        <span>{{ orderInfo.carNumber }}</span>
      </li>
      <li class="order_item order_item_1">
        <span>车架号:</span>
        <span>{{ contractItems.item_7 }}</span>
      </li>
      <li class="order_item order_item_2">
        <span
          >签字状态:
          <el-button link type="success" v-if="contractInfo.signature"
            >已签字</el-button
          ><el-button v-else link type="warning">待签字</el-button></span
        >
        <el-button
          v-if="!contractInfo.signature"
          type="primary"
          size="small"
          @click="goToContractInfo"
          >去签字</el-button
        >
        <el-button v-else type="success" size="small" link
          ><el-icon><Check /></el-icon>已完成</el-button
        >
      </li>
      <li class="order_item order_item_3" v-if="contractInfo.signature">
        <span
          >支付状态:<el-button
            link
            type="success"
            v-if="orderInfo.payStatus == 1"
            >已支付</el-button
          ><el-button v-else link type="warning">待支付</el-button></span
        >
        <span v-if="orderInfo.payStatus != 1">
          <el-button type="primary" size="small" @click="goToPay"
            >去支付</el-button
          >
        </span>
      </li>
    </ul>
  </div>
</template>

<style scoped>
.order_signature_view {
  width: 100vw;
  height: 100vh;
  background-color: #f2f2f2;
}
.order_signature {
  padding: 0;
}
.order_signature .order_item {
  background-color: #fff;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 45px;
  padding: 0 15px;
  box-sizing: border-box;
  position: relative;
}
.order_signature .order_item::after {
  content: "";
  height: 1px;
  background-color: #000;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  transform: scaleY(0.1);
}
.order_signature .order_item_1 {
  margin-bottom: 15px;
}
.order_signature .order_item_1::after {
  content: "";
  height: 0;
}
.order_signature .order_item_2::after {
  content: "";
  height: 0;
}
.order_item_3::after {
  content: "";
  height: 1px;
  background-color: #000;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  transform: scaleY(0.1);
}
</style>